import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate

# 中文和负号的正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 直角坐标下弧长计算
def arc_length_cartesian(f, f_prime, a, b):
    """
    计算直角坐标系下曲线的弧长
    f: 函数
    f_prime: 函数的导数
    a, b: 积分区间
    """
    def integrand(x):
        return np.sqrt(1 + f_prime(x)**2)
    
    length, error = integrate.quad(integrand, a, b)
    return length, error

# 示例：y = (2/3)x^(3/2) 在 [0,3] 上的弧长
def f3(x):
    return (2/3) * x**(3/2)

def f3_prime(x):
    return np.sqrt(x)

length1, error1 = arc_length_cartesian(f3, f3_prime, 0, 3)
print(f"曲线弧长: {length1:.6f} (理论值: {14/3:.6f})")

# 可视化曲线
x = np.linspace(0, 3, 100)
y = f3(x)

plt.figure(figsize=(8, 6))
plt.plot(x, y, 'b-', linewidth=2, label='$y = \\frac{2}{3}x^{3/2}$')
plt.xlabel('x')
plt.ylabel('y')
plt.title('曲线弧长计算示例')
plt.grid(True)
plt.legend()

# 标注弧长
plt.text(1.5, 2, f'弧长 L = {length1:.4f}', fontsize=12, 
         bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.7))

plt.show()